<template>
  <div class="sn-container">
    <div class="container">
      <el-row>
        <el-col :xl="24" :lg="24" style="border-right: 1px solid #dcdfe6">
          <div style="padding-left: 10px">
            <div class="handle-box">
              <el-form :model="queryParams" ref="queryForm" :inline="true">
                <!-- 动态渲染搜索条件 -->
                <el-form-item
                  v-for="condition in snListColum.searchConditions"
                  :key="condition.name"
                  :label="condition.label"
                  :prop="condition.name"
                >
                  <!-- 输入框 -->
                  <el-input
                    v-if="condition.type === 'input' || condition.type === 'string'"
                    v-model="queryParams[condition.name]"
                    :placeholder="condition.placeholder"
                  />
                  <!-- 选择框 -->
                  <el-select
                    v-else-if="condition.type === 'select'"
                    v-model="queryParams[condition.name]"
                    :placeholder="condition.placeholder"
                  >
                    <el-option
                      v-for="option in condition.options"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                    />
                  </el-select>
                  <!-- 日期范围选择器 -->
                  <el-date-picker
                    v-else-if="condition.type === 'datetimerange'"
                    v-model="queryParams[condition.name]"
                    type="datetimerange"
                    :placeholder="condition.placeholder"
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  />
                  <!-- 日期范围选择器 -->
                  <el-date-picker
                    v-else-if="condition.type === 'datepickerrange'"
                    v-model="queryParams[condition.name]"
                    type="daterange"
                    :placeholder="condition.placeholder"
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  />
                </el-form-item>
                
                <!-- 搜索按钮 -->
                <el-form-item>
                  <el-button type="primary" :icon="Plus" @click="openAddDialog">新增</el-button>
                  <el-button type="primary" @click="handleSearch">查询</el-button>
                  <el-upload
                    class="upload-area"
                    action="#"
                    :http-request="uploadFile"
                    :auto-upload="true"
                    :on-change="handleFileChange"
                    ref="uploadRef"
                    accept=".xlsx, .xls"
                    :limit="1"
                  >
                    <el-button type="primary" class="m-2">上传文件</el-button>
                  </el-upload>
                  <el-button type="primary" @click="downloadTemplate">下载模板</el-button>
                  <!-- <el-button>导入Excel</el-button> -->
                </el-form-item>
              </el-form>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
              <el-table-column
                v-for="column in snListColum.properties"
                :key="column.name"
                :prop="column.name"
                :label="column.label"
                :align="getColumnAlign(column)"
                :fixed="column.fixed"
              />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button text :icon="Edit" @click="handleEdit('edit', scope.row)">
                    编辑
                  </el-button>
                  <el-button text :icon="Delete" class="red" @click="handleEdit('delete', scope.row)">
                    删除
                  </el-button>
                  </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination
                background
                layout="total, prev, pager, next"
                :current-page="query.pageNum"
                :page-size="query.pageSize"
                :total="pageTotal"
                @current-change="handlePageChange"
              ></el-pagination>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 新增 -->
    <el-dialog title="新增" v-model="addVisible" width="40%">
      <el-form :model="snForm" ref="addForm">
        <!-- 动态渲染搜索条件 -->
        <el-form-item
          v-for="condition in snListColum.addProperties"
          :key="condition.name"
          :label="condition.label"
          :prop="condition.name"
        >
          <!-- 输入框 -->
          <el-input
            v-if="(condition.type === 'input' || condition.type === 'string') && condition.editable"
            v-model="snForm[condition.name]"
            :placeholder="condition.placeholder"
            clearable
          />
          <!-- 选择框 -->
          <el-select
            v-else-if="condition.type === 'select'"
            v-model="snForm[condition.name]"
            :placeholder="condition.placeholder"
            clearable
          >
            <el-option
              v-for="option in condition.options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <!-- 日期范围选择器 -->
          <el-date-picker
            v-else-if="condition.type === 'datetime'"
            v-model="snForm[condition.name]"
            type="datetime"
            :placeholder="condition.placeholder"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          <el-date-picker
            v-else-if="condition.type === 'datepicker'"
            v-model="snForm[condition.name]"
            type="date"
            :placeholder="condition.placeholder"
            value-format="YYYY-MM-DD"
          />
          <!-- 长文本 -->
          <el-input
            v-else-if="condition.type === 'textarea'"
            v-model="snForm[condition.name]"
            :type="condition.type"
            :placeholder="condition.placeholder"
          />
          <el-input-number
            v-else-if="condition.type === 'int'"
            v-model="snForm[condition.name]"
            :precision="0"
            :step="1"
          />
          <el-input-number
            v-else-if="condition.type === 'float'"
            v-model="snForm[condition.name]"
            :precision="2"
            :step="0.1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="addVisible = false">取 消</el-button>
					<el-button type="primary" @click="saveSNData('add')">确 定</el-button>
				</span>
      </template>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog title="编辑" v-model="editVisible" width="40%">
      <el-form :model="snForm" ref="queryForm">
        <!-- 动态渲染搜索条件 -->
        <el-form-item
          v-for="condition in snListColum.properties"
          :key="condition.name"
          :label="condition.label"
          :prop="condition.name"
        >
          <!-- 输入框 -->
          <el-input
            v-if="condition.type === 'input' || condition.type === 'string'"
            :disabled="!condition.editable"
            v-model="snForm[condition.name]"
            :placeholder="condition.placeholder"
            clearable
          />
          <!-- 选择框 -->
          <el-select
            v-else-if="condition.type === 'select'"
            v-model="snForm[condition.name]"
            :placeholder="condition.placeholder"
            clearable
          >
            <el-option
              v-for="option in condition.options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <el-date-picker
            v-else-if="condition.type === 'datetime'"
            v-model="snForm[condition.name]"
            type="datetime"
            :placeholder="condition.placeholder"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          <el-date-picker
            v-else-if="condition.type === 'datepicker'"
            v-model="snForm[condition.name]"
            type="date"
            :placeholder="condition.placeholder"
            value-format="YYYY-MM-DD"
          />
          <el-input-number
            v-else-if="condition.type === 'int'"
            v-model="snForm[condition.name]"
            :precision="0"
            :step="1"
          />
          <el-input-number
            v-else-if="condition.type === 'float'"
            v-model="snForm[condition.name]"
            :precision="2"
            :step="0.1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="editVisible = false">取 消</el-button>
					<el-button type="primary" @click="saveSNData('update')">确 定</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {reactive, ref, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Edit, Plus} from '@element-plus/icons-vue';
import { addData, getManagerData, getDataList, updateData, deleteData, importData, getImportDataTemplate } from "@/api/dataManage";


const snListColum = ref<any>({});

interface TableItem {
  id: number;
  name: string;
  location: string;
  time: string;
  description: string;
  level: string;
}

const snForm = ref<any>({});
const query = reactive({
  pageNum: 1,
  pageSize: 10
});
const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
const addVisible = ref(false);
const editVisible = ref(false);
const fileData = ref<any>(null);
const uploadRef = ref();
// 初始化表单数据
const initForm = () => {
  const formData: any = {};
  
  if (snListColum.value.properties && Array.isArray(snListColum.value.properties)) {
    snListColum.value.properties.forEach((property: any) => {
      switch (property.type) {
        case 'select':
          formData[property.name] = property.options?.[0]?.value || '';
          break;
        case 'daterange':
          formData[property.name] = [];
          break;
        case 'datetime':
          formData[property.name] = '';
          break;
        default:
          formData[property.name] = '';
      }
    });
  }
  
  return formData;
};

// 初始化查询参数
const initQueryParams = () => {
  const params: any = {};
  // snListColum.value.searchConditions = snJson.searchConditions;
  if (snListColum.value.searchConditions) {
    snListColum.value.searchConditions.forEach((condition: any) => {
      if (condition.type === 'daterange'  || condition.type === 'datetime') {
        params[condition.name] = [];
      } else if (condition.type === 'select') {
        params[condition.name] = condition.options[0]?.value || '';
      } else {
        params[condition.name] = '';
      }
    });
  }
  return params;
};

const queryParams = reactive(initQueryParams());

// 获取列的对齐方式
const getColumnAlign = (column: any) => {
  if (column.type === 'image') return 'center';
  if (column.name === 'state') return 'center';
  return 'left';
};
const uploadFile = () => {
  const uploadFormdata = new FormData();
  uploadFormdata.append('file', fileData.value);
  uploadFormdata.append('dataType', "railwayTrain");
  return importData(uploadFormdata).then(result => {
    console.log("result is ", result);
    if (result.data.success) {
      ElMessage.success('上传成功');
      fileData.value = null;
      uploadRef.value.clearFiles();
    }
  }).catch(error => {
    console.log("error is ", error);
    ElMessage.error('上传失败');
    fileData.value = null;
    uploadRef.value.clearFiles();
  });
};

const handleFileChange = (file: any) => {
  console.log("file is ", file);
  // 验证文件类型
  const allowedTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  if (!allowedTypes.includes(file.raw.type)) {
    ElMessage.error('只能上传Excel文件！');
    return;
  }

  // 验证文件大小
  const maxSize = 2 * 1024 * 1024; // 10MB
  if (file.raw.size > maxSize) {
    ElMessage.error('文件大小不能超过2MB！');
    return;
  }

  fileData.value = file.raw;
};

const downloadTemplate = async () => {
  getImportDataTemplate({dataType: 'railwayTrain'}).then(result => {
    if (result.data.success) {
      window.open(result.data.data);
      ElMessage.error('模板获取成功，浏览器下载中！');
    }
  }).catch(error => {
    ElMessage.error('文件下载失败！');
  });
}

// 保存数据
const saveSNData = async (saveType: string) => {
  try {
    console.log("snForm is ", snForm.value);
    const newFormData = JSON.parse(JSON.stringify(snForm.value));
    newFormData.time = "2025-01-25 12:12:12";
    let snRes: any;
    if (saveType === 'add') {
      delete newFormData.id;
      snRes = await addData({
        dataType: "railwayTrain",
        data: newFormData
      });
    } else {
      snRes = await updateData({
        dataType: "railwayTrain",
        data: newFormData
      });
    }

    console.log("snRes is ", snRes);
    ElMessage.success('保存成功');
    addVisible.value = false;
    editVisible.value = false;
    await fetchTableData(); // 重新加载表格数据
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error('保存失败');
  }
}

// 获取表格数据
const fetchTableData = async () => {
  try {
    const res = await getDataList({
      dataType: "railwayTrain",
      pageNum : query.pageNum,
      pageSize: query.pageSize,
      params: {
        ...queryParams
      }
    });
    console.log("getDataList 获取数据成功:", res);
    tableData.value = res.data.data.records;
    pageTotal.value = res.data.data.total;
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error('获取数据失败');
  }
};

// 初始化数据
const initData = async () => {
  try {
    // 获取管理数据配置
    const managerRes = await getManagerData();
    console.log("getManagerData res is ", managerRes);
    
    // 过滤出交通事件类型
    snListColum.value = managerRes.data.data.find((item: any) => {
      return item.type === "railwayTrain";
    }) || {};
    snListColum.value.addProperties = snListColum.value.properties.filter((property: any) => {
      return property.editable;
    });
    // 初始化表单数据
    snForm.value = reactive(initForm());
    console.log("snForm.value ", snForm.value);
    // 初始化查询参数
    Object.assign(queryParams, initQueryParams());
    
    // 获取表格数据
    await fetchTableData();
  } catch (error) {
    console.error("初始化失败:", error);
    ElMessage.error('初始化失败');
  }
};

// 组件挂载时初始化数据
onMounted(() => {
  initData();
});

// 查询操作
const handleSearch = async () => {
  query.pageNum = 1;
  await fetchTableData();
};

// 分页导航
const handlePageChange = async (val: number) => {
  query.pageNum = val;
  await fetchTableData();
};

// 处理编辑
const handleEdit = (types: string, row: any) => {
  if (types === 'edit') {
    // 填充表单数据
    Object.keys(snForm.value).forEach(key => {
      if (row[key] !== undefined) {
        snForm.value[key] = row[key];
      }
    });
    editVisible.value = true;
  } else if (types === 'delete') {
    handleDelete(row);
  }
};

// 处理删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除吗？', '提示', {
      type: 'warning'
    });
    // 这里调用删除API
    await deleteData({ dataType: "railwayTrain", dataId: row.id });
    ElMessage.success('删除成功');
    await fetchTableData(); // 重新加载数据
  } catch (error) {
    console.log("取消删除");
  }
};

// 打开新增对话框
const openAddDialog = () => {
  // 重置表单数据
  Object.assign(snForm.value, initForm());
  addVisible.value = true;
};
</script>

<style lang="scss" scoped>
.sn-container {
  :deep(.el-select) {
    min-width: 120px;
  }
  .container {
    :deep(.el-form-item__content) {
      .upload-area {
        .el-upload {
          .el-button {
            margin: 0 10px;
          }
        }
        .el-upload-list {
          display: none;
        }
      }
    }
  }
  .el-overlay {
    .el-overlay-dialog {
      .el-dialog {
        .el-dialog__body {
          .el-form {
            .el-form-item {
              :deep(.el-form-item__label) {
                width: 100px;
              }
              :deep(.el-input-number) {
                width: 220px;
              }
            }
          }
        }
      }
    }
  }
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #F56C6C;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

</style>
